import 'package:account_book/common/constants/storage_key.dart';
import 'package:account_book/common/dao/category_dao.dart';
import 'package:account_book/common/dao/history_dao.dart';
import 'package:account_book/common/entity/category.dart';
import 'package:account_book/common/entity/history.dart';
import 'package:account_book/common/services/storage_service.dart';
import 'package:account_book/common/utils/toast_util.dart';
import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import './index.dart';

class EnrollController extends GetxController {
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  final state = EnrollState();

  @override
  void onReady() {
    super.onReady();
    _loadCategoryData();
  }

  /// 加载数据
  void _loadCategoryData() async {
    List<Category> list = await CategoryDao.instance.getListByType(state.type);
    state.categoryData.clear();
    if (list.isNotEmpty) {
      state.categoryData.addAll(list);
    }
  }

  void switchType(int type) {
    state.type = type;
    _loadCategoryData();
  }

  /// 保存费用
  Future<void> saveExpense() async {
    final currentBookId =
        StorageService.instance.getInt(StorageKeyConstants.currentBook);
    if (currentBookId == null) {
      ToastUtil.show("请先设置账本");
      return;
    }
    History history =
        History(bookId: currentBookId, categoryId: state.categoryId);
    history.categoryName = state.categoryName;
    history.amount = double.parse(state.amount);
    history.type = state.type;
    history.createDate = state.createDate;
    history.remark = state.remark;
    await HistoryDao.instance.insert(history.toMap());
    ToastUtil.show("保存成功");
    Get.back();
  }
}
